/*
 * Niiuzu
 * Copyright (C) 2011  Thierry Nowak
 * 
 * This program is free software: you can redistribute it and/or modify it under
 * the terms of the GNU General Public License as published by the Free Software
 * Foundation, either version 3 of the License, or (at your option) any later
 * version.
 * 
 * This program is distributed in the hope that it will be useful, but WITHOUT
 * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS
 * FOR A PARTICULAR PURPOSE.  See the GNU General Public License for more
 * details.
 * 
 * You should have received a copy of the GNU General Public License along with
 * this program.  If not, see <http://www.gnu.org/licenses/>.
 */
package com.niiuzu.client.util.widget;

import java.util.HashMap;
import java.util.Map;

import com.google.gwt.user.client.ui.ListBox;

/**
 * {@link ListBox} dont les valeurs sont directement accessibles.
 * 
 * @param <T>
 *            type de la valeur qui sera gérée par la {@link ListBox}.
 */
public class ListBoxValue<T> extends ListBox implements HasSelectedValue<T> {

	private Map<Integer, T> valuesMap = new HashMap<Integer, T>();

	@Override
	public void addValue(String labelItem, T value) {
		int itemCount = this.getItemCount();

		this.addItem(labelItem);

		valuesMap.put(itemCount, value);
	}

	@Override
	public T getSelectedValue() {
		int selectedIndex = getSelectedIndex();
		return valuesMap.get(selectedIndex);
	}

	@Override
	public void setSelectedValue(T selectedValue) {
		Integer index = getIndexFromValue(selectedValue);
		if (index != null) {
			this.setSelectedIndex(index.intValue());
		}
	}

	/**
	 * Retrouve l'index sélectionné à partir de la valeur.
	 * 
	 * @param value
	 *            valeur permettant de retrouver une ligne dans la liste.
	 * 
	 * @return index de la ligne correspondant à la valeur, ou <tt>null</tt> si
	 *         il n'y a pas de correspondance.
	 */
	private Integer getIndexFromValue(T someValue) {
		for (Integer valueIndex : valuesMap.keySet()) {
			T value = valuesMap.get(valueIndex);
			if ((someValue == null && value == null)
					|| (someValue != null && someValue.equals(value))) {
				return valueIndex;
			}
		}

		return null;
	}

	@Override
	public void clear() {
		super.clear();

		valuesMap.clear();
	}

}
